package com.example.library.util;

import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.example.library.model.ReservationHistory;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LocalStorageManager {
    private static final String PREF_NAME = "LibraryAppPrefs";
    private static final String KEY_USER_ID = "userId";
    private static final String KEY_NICKNAME = "nickname";
    private static final String KEY_AVATAR_URI = "avatarUri";
    private static final String KEY_IS_LOGGED_IN = "isLoggedIn";
    private static final String KEY_HALL_SEATS = "hall_seats";
    private static final String KEY_SINGLE_ROOMS = "single_rooms";
    private static final String KEY_GROUP_ROOMS = "group_rooms";
    private static final String KEY_RESERVATION_HISTORY = "reservation_history";
    
    private final SharedPreferences sharedPreferences;
    private final Gson gson;
    
    public LocalStorageManager(Context context) {
        sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        gson = new Gson();
    }
    
    public void saveUserData(String userId, String nickname) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_USER_ID, userId);
        editor.putString(KEY_NICKNAME, nickname);
        editor.putBoolean(KEY_IS_LOGGED_IN, true);
        editor.apply();
    }
    
    public void saveAvatarUri(String avatarUri) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_AVATAR_URI, avatarUri);
        editor.apply();
    }
    
    public String getUserId() {
        return sharedPreferences.getString(KEY_USER_ID, "");
    }
    
    public String getNickname() {
        return sharedPreferences.getString(KEY_NICKNAME, "");
    }
    
    public String getAvatarUri() {
        return sharedPreferences.getString(KEY_AVATAR_URI, "");
    }
    
    public boolean isLoggedIn() {
        return sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
    }
    
    public void clearUserData() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
    }
    
    // 保存大厅座位状态
    public void saveHallSeatStatus(String seatNumber, String status, String userId) {
        Map<String, SeatInfo> seatMap = getHallSeatsStatus();
        SeatInfo oldInfo = seatMap.get(seatNumber);
        seatMap.put(seatNumber, new SeatInfo(status, userId));
        sharedPreferences.edit()
                .putString(KEY_HALL_SEATS, gson.toJson(seatMap))
                .apply();
        
        // 添加到预约历史（包括取消预约）
        if ("空闲".equals(status) && oldInfo != null && oldInfo.getUserId() != null) {
            // 这是取消预约的情况
            addReservationHistory(new ReservationHistory(
                seatNumber,
                ReservationHistory.TYPE_HALL_SEAT,
                "已取消",
                oldInfo.getUserId()
            ));
        } else if (userId != null) {
            // 这是新预约的情况
            addReservationHistory(new ReservationHistory(
                seatNumber,
                ReservationHistory.TYPE_HALL_SEAT,
                status,
                userId
            ));
        }
    }
    
    // 获取大厅座位状态
    public Map<String, SeatInfo> getHallSeatsStatus() {
        String json = sharedPreferences.getString(KEY_HALL_SEATS, "");
        if (json.isEmpty()) {
            return new HashMap<>();
        }
        Type type = new TypeToken<Map<String, SeatInfo>>(){}.getType();
        return gson.fromJson(json, type);
    }
    
    // 保存单人研修室状态
    public void saveSingleRoomStatus(String roomNumber, String status, String userId) {
        Map<String, SeatInfo> roomMap = getSingleRoomsStatus();
        SeatInfo oldInfo = roomMap.get(roomNumber);
        roomMap.put(roomNumber, new SeatInfo(status, userId));
        sharedPreferences.edit()
                .putString(KEY_SINGLE_ROOMS, gson.toJson(roomMap))
                .apply();
                
        // 添加到预约历史（包括取消预约）
        if ("空闲".equals(status) && oldInfo != null && oldInfo.getUserId() != null) {
            // 这是取消预约的情况
            addReservationHistory(new ReservationHistory(
                roomNumber,
                ReservationHistory.TYPE_SINGLE_ROOM,
                "已取消",
                oldInfo.getUserId()
            ));
        } else if (userId != null) {
            // 这是新预约的情况
            addReservationHistory(new ReservationHistory(
                roomNumber,
                ReservationHistory.TYPE_SINGLE_ROOM,
                status,
                userId
            ));
        }
    }
    
    // 获取单人研修室状态
    public Map<String, SeatInfo> getSingleRoomsStatus() {
        String json = sharedPreferences.getString(KEY_SINGLE_ROOMS, "");
        if (json.isEmpty()) {
            return new HashMap<>();
        }
        Type type = new TypeToken<Map<String, SeatInfo>>(){}.getType();
        return gson.fromJson(json, type);
    }
    
    // 保存小组讨论室状态
    public void saveGroupRoomStatus(String roomNumber, String status, String userId) {
        Map<String, SeatInfo> roomMap = getGroupRoomsStatus();
        SeatInfo oldInfo = roomMap.get(roomNumber);
        roomMap.put(roomNumber, new SeatInfo(status, userId));
        sharedPreferences.edit()
                .putString(KEY_GROUP_ROOMS, gson.toJson(roomMap))
                .apply();
                
        // 添加到预约历史（包括取消预约）
        if ("空闲".equals(status) && oldInfo != null && oldInfo.getUserId() != null) {
            // 这是取消预约的情况
            addReservationHistory(new ReservationHistory(
                roomNumber,
                ReservationHistory.TYPE_GROUP_ROOM,
                "已取消",
                oldInfo.getUserId()
            ));
        } else if (userId != null) {
            // 这是新预约的情况
            addReservationHistory(new ReservationHistory(
                roomNumber,
                ReservationHistory.TYPE_GROUP_ROOM,
                status,
                userId
            ));
        }
    }
    
    // 获取小组讨论室状态
    public Map<String, SeatInfo> getGroupRoomsStatus() {
        String json = sharedPreferences.getString(KEY_GROUP_ROOMS, "");
        if (json.isEmpty()) {
            return new HashMap<>();
        }
        Type type = new TypeToken<Map<String, SeatInfo>>(){}.getType();
        return gson.fromJson(json, type);
    }
    
    // 添加预约历史记录
    private void addReservationHistory(ReservationHistory history) {
        List<ReservationHistory> historyList = getReservationHistory();
        historyList.add(0, history); // 添加到列表开头
        sharedPreferences.edit()
                .putString(KEY_RESERVATION_HISTORY, gson.toJson(historyList))
                .apply();
    }
    
    // 获取预约历史记录
    public List<ReservationHistory> getReservationHistory() {
        String json = sharedPreferences.getString(KEY_RESERVATION_HISTORY, "");
        if (json.isEmpty()) {
            return new ArrayList<>();
        }
        Type type = new TypeToken<List<ReservationHistory>>(){}.getType();
        return gson.fromJson(json, type);
    }
    
    // 获取指定用户的预约历史记录
    public List<ReservationHistory> getReservationHistoryForUser(String userId) {
        List<ReservationHistory> allHistory = getReservationHistory();
        List<ReservationHistory> userHistory = new ArrayList<>();
        for (ReservationHistory history : allHistory) {
            if (userId.equals(history.getUserId())) {
                userHistory.add(history);
            }
        }
        return userHistory;
    }
    
    // 清除所有本地存储的预约状态
    public void clearAllReservations() {
        sharedPreferences.edit()
                .remove(KEY_HALL_SEATS)
                .remove(KEY_SINGLE_ROOMS)
                .remove(KEY_GROUP_ROOMS)
                .remove(KEY_RESERVATION_HISTORY)
                .apply();
    }
    
    // 删除指定用户的指定预约历史记录
    public void deleteReservationHistory(String userId, long timestamp) {
        List<ReservationHistory> allHistory = getReservationHistory();
        List<ReservationHistory> updatedHistory = new ArrayList<>();
        
        for (ReservationHistory history : allHistory) {
            if (!(userId.equals(history.getUserId()) && timestamp == history.getTimestamp())) {
                updatedHistory.add(history);
            }
        }
        
        sharedPreferences.edit()
                .putString(KEY_RESERVATION_HISTORY, gson.toJson(updatedHistory))
                .apply();
    }
    
    // 删除指定用户的所有预约历史记录
    public void deleteAllReservationHistoryForUser(String userId) {
        List<ReservationHistory> allHistory = getReservationHistory();
        List<ReservationHistory> updatedHistory = new ArrayList<>();
        
        for (ReservationHistory history : allHistory) {
            if (!userId.equals(history.getUserId())) {
                updatedHistory.add(history);
            }
        }
        
        sharedPreferences.edit()
                .putString(KEY_RESERVATION_HISTORY, gson.toJson(updatedHistory))
                .apply();
    }
    
    // 内部类用于存储座位/房间信息
    public static class SeatInfo {
        private String status;
        private String userId;
        
        public SeatInfo(String status, String userId) {
            this.status = status;
            this.userId = userId;
        }
        
        public String getStatus() {
            return status;
        }
        
        public String getUserId() {
            return userId;
        }
    }
} 